<%--
  Created by IntelliJ IDEA.
  User: LLLzy
  Date: 2025/6/18
  Time: 08:56
  To change this template use File | Settings | File Templates.
--%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

<c:set var="title" value="批次管理"/>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <style>
        body {
            font-size: .875rem;
        }
        .sidebar {
            position: fixed;
            top: 0;
            bottom: 0;
            left: 0;
            z-index: 100;
            padding: 48px 0 0;
            box-shadow: inset -1px 0 0 rgba(0, 0, 0, .1);
        }
        .sidebar-sticky {
            position: relative;
            top: 0;
            height: calc(100vh - 48px);
            padding-top: .5rem;
            overflow-x: hidden;
            overflow-y: auto;
        }
    </style>
</head>
<body>
    <%@ include file="../common/header.jsp" %>

    <div class="main-content">
        <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
            <h1 class="h2">${title}</h1>
            <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addBatchModal">
                <i class="fa-solid fa-plus-circle"></i> 添加批次
            </button>
        </div>
        <!-- 批次概览 -->
        <div class="row mb-4">
            <div class="col-md-3">
                <div class="card">
                    <div class="card-body">
                        <h5 class="card-title">今日入库人参数</h5>
                        <p class="card-text display-6">${todayInCount}</p>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card">
                    <div class="card-body">
                        <h5 class="card-title">本周完成</h5>
                        <p class="card-text display-6">${weekChecked}</p>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card">
                    <div class="card-body">
                        <h5 class="card-title">完成率</h5>
                        <p class="card-text display-6">${completionRate}%</p>
                    </div>
                </div>
            </div>


            <!-- 播种采收专项按钮 -->
            <div class="col-md-3 d-flex align-items-stretch">
                <button class="btn btn-primary btn-lg w-100 d-flex align-items-center justify-content-center"
                        style="min-height: 100%;" onclick="showSowHarvestModal()">
                    <i class="fa-solid fa-seedling me-2"></i> 人参溯源码批次管理
                </button>
            </div>

        </div>
        <!-- 批次列表 -->
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">批次列表</h5>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-striped">
                        <thead>
                            <tr>
                                <th>批次编号</th>
                                <th>初始人参数量</th>
                                <th>基地ID</th>
                                <th>初质检</th>
                                <th>二次质检</th>
                                <th>创建时间</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            <c:forEach var="batch" items="${batchList}">
                                <tr>
                                    <td>${batch.batchNo}</td>
                                    <td>${batch.initParamCount}</td>
                                    <td>${batch.sourceBaseId}</td>
                                    <td>${batch.check1}</td>
                                    <td>${batch.check2}</td>
                                    <td><fmt:formatDate value="${batch.createDate}" pattern="yyyy-MM-dd"/></td>
                                    <td>
                                        <button class="btn btn-sm btn-primary" onclick="showEditModal('${batch.batchNo}')">修改</button>
                                    </td>
                                </tr>
                            </c:forEach>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    <!-- 添加批次模态框 -->
    <div class="modal fade" id="addBatchModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <form id="addBatchForm">
                    <div class="modal-header">
                        <h5 class="modal-title">添加批次</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <div class="mb-3">
                            <label class="form-label">批次号</label>
                            <input type="text" class="form-control" name="batchNo" id="addBatchNo" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">基地ID</label>
                            <input type="number" class="form-control" name="sourceBaseId" id="addSourceBaseId" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">人参数量</label>
                            <input type="number" class="form-control" name="initParamCount" id="addInitParamCount" required>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-primary" onclick="submitAddBatch()">保存</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <!-- 批次编辑模态框 -->
    <div class="modal fade" id="editBatchModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <form id="editBatchForm">
                    <div class="modal-header">
                        <h5 class="modal-title">批次信息详情与编辑</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <input type="hidden" name="batchNo" id="editBatchNo">

                        <div class="row">
                            <!-- 左侧：只读信息 -->
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label fw-bold">批次号</label>
                                    <p class="form-control-plaintext bg-light p-2 rounded" id="displayBatchNo"></p>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label fw-bold">基地ID</label>
                                    <p class="form-control-plaintext bg-light p-2 rounded" id="displaySourceBaseId"></p>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label fw-bold">成立日期</label>
                                    <p class="form-control-plaintext bg-light p-2 rounded" id="displayCreateDate"></p>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label fw-bold">状态</label>
                                    <p class="form-control-plaintext bg-light p-2 rounded" id="displayStatus"></p>
                                </div>
                            </div>

                            <!-- 右侧：可编辑信息 -->
                            <div class="col-md-6">
                                <!-- initParamCount字段 - 根据status动态显示 -->
                                <div class="mb-3" id="initParamCountGroup">
                                    <label class="form-label fw-bold">初始人参数量</label>
                                    <input type="number" class="form-control" name="initParamCount" id="editInitParamCount" required>
                                </div>

                                <!-- 质检状态字段 -->
                                <div class="mb-3">
                                    <label class="form-label fw-bold">初质检</label>
                                    <select class="form-select" name="check1" id="editCheck1" required>
                                        <option value="未质检">未质检</option>
                                        <option value="已质检">已质检</option>
                                        <option value="合格">合格</option>
                                        <option value="不合格">不合格</option>
                                    </select>
                                </div>

                                <div class="mb-3">
                                    <label class="form-label fw-bold">二次质检</label>
                                    <select class="form-select" name="check2" id="editCheck2" required>
                                        <option value="未质检">未质检</option>
                                        <option value="已质检">已质检</option>
                                        <option value="合格">合格</option>
                                        <option value="不合格">不合格</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-primary" onclick="submitEditBatch()">保存</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- 人参溯源码管理模态框 -->
    <div class="modal fade" id="sowHarvestModal" tabindex="-1">
        <div class="modal-dialog modal-xl">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">人参溯源码批次管理</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="table-responsive">
                        <table class="table table-striped table-hover">
                            <thead class="table-dark">
                            <tr>
                                <th>批次编号</th>
                                <th>初始人参数量</th>
                                <th>基地ID</th>
                                <th>创建日期</th>
                                <th>操作</th>
                            </tr>
                            </thead>
                            <tbody id="sowHarvestTableBody">
                            <!-- 数据将通过JavaScript动态填充 -->
                            </tbody>
                        </table>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    </div>

    <%@ include file="../common/footer.jsp" %>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <script>
        function viewBatchDetails(batchId) {
            // 实现查看批次详情功能
        }
        function editBatch(batchId) {
            // 实现编辑批次功能
        }
        function deleteBatch(batchId) {
            // 实现删除批次功能
        }
        function submitAddBatch() {
            var formData = {
                batchNo: $('#addBatchNo').val(),
                sourceBaseId: $('#addSourceBaseId').val(),
                initParamCount: $('#addInitParamCount').val()
            };
            $.ajax({
                url: '${pageContext.request.contextPath}/processing/addBatch',
                type: 'POST',
                data: JSON.stringify(formData),
                contentType: 'application/json',
                success: function(res) {
                    $('#addBatchModal').modal('hide');
                    location.reload();
                },
                error: function() {
                    alert('保存失败，请重试');
                }
            });
        }
        window.batchList = [
            <c:forEach var="batch" items="${batchList}" varStatus="s">
            {
                batchNo: '${batch.batchNo}',
                initParamCount: '${batch.initParamCount}',
                sourceBaseId: '${batch.sourceBaseId}',
                createDate: '${batch.createDate}',
                check1: '${batch.check1}',
                check2: '${batch.check2}',
                status: '${batch.status}'  // 添加status字段
            }<c:if test="${!s.last}">,</c:if>
            </c:forEach>
        ];

        function showEditModal(batchNo) {
            var batch = window.batchList.find(b => b.batchNo === batchNo);
            if (!batch) return;

            // 设置隐藏的批次号（用于表单提交）
            $('#editBatchNo').val(batch.batchNo);

            // 显示所有信息（包括只读信息）
            $('#displayBatchNo').text(batch.batchNo);
            $('#displaySourceBaseId').text(batch.sourceBaseId || '无');
            $('#displayCreateDate').text(batch.createDate ? batch.createDate.substr(0,10) : '无');
            $('#displayStatus').text(batch.status || '无');

            // 设置可编辑字段
            $('#editInitParamCount').val(batch.initParamCount);
            $('#editCheck1').val(batch.check1);
            $('#editCheck2').val(batch.check2);

            // 根据status值控制initParamCount字段的显示
            if (batch.status) {
                // status不为空，隐藏initParamCount输入框
                $('#initParamCountGroup').hide();
            } else {
                // status为空，显示initParamCount输入框
                $('#initParamCountGroup').show();
            }

            // 智能控制质检状态
            if(batch.check1 === '未质检') {
                $('#editCheck2').val('未质检').prop('disabled', true);
            } else {
                $('#editCheck2').prop('disabled', false);
            }

            $('#editBatchModal').modal('show');
        }

        // 初检状态变化事件（放在页面加载时执行）
        $(document).ready(function() {
            $('#editCheck1').on('change', function() {
                if ($(this).val() === '未质检') {
                    $('#editCheck2').val('未质检').prop('disabled', true);
                } else {
                    $('#editCheck2').prop('disabled', false);
                }
            });
        });
        function submitEditBatch() {
            var formData = {
                batchNo: $('#editBatchNo').val(),
                initParamCount: $('#editInitParamCount').val(),
                sourceBaseId: $('#editSourceBaseId').val(),
                createDate: $('#editCreateDate').val(),
                check1: $('#editCheck1').val(),
                check2: $('#editCheck2').val()
            };
            $.ajax({
                url: '${pageContext.request.contextPath}/processing/updateBatch',
                type: 'POST',
                data: JSON.stringify(formData),
                contentType: 'application/json',
                success: function(res) {
                    $('#editBatchModal').modal('hide');
                    location.reload();
                },
                error: function() {
                    alert('保存失败，请重试');
                }
            });
        }

        // 显示人参溯源码管理模态框
        function showSowHarvestModal() {
            // 获取status为空的批次数据
            fetch('${pageContext.request.contextPath}/production/getBatchesWithNullStatus')
                .then(response => response.json())
                .then(data => {
                    populateSowHarvestTable(data);
                    $('#sowHarvestModal').modal('show');
                })
                .catch(error => {
                    console.error('Error fetching batches:', error);
                    alert('获取批次数据失败');
                });
        }

        // 填充表格数据
        function populateSowHarvestTable(batches) {
            const tableBody = document.getElementById('sowHarvestTableBody');
            tableBody.innerHTML = ''; // 清空现有数据

            if (batches.length === 0) {
                tableBody.innerHTML = `
            <tr>
                <td colspan="5" class="text-center text-muted py-4">
                    <i class="fa-solid fa-inbox me-2"></i>暂无待处理的批次数据
                </td>
            </tr>
        `;
                return;
            }

            batches.forEach(batch => {
                const row = document.createElement('tr');
                row.innerHTML = `
            <td>${batch.batchNo}</td>
            <td>${batch.initParamCount}</td>
            <td>${batch.sourceBaseId}</td>
            <td>${batch.createDate ? batch.createDate.substr(0,10) : '无'}</td>
            <td>
                <button class="btn btn-success btn-sm"
                        onclick="generateTraceCodes('${batch.batchNo}', ${batch.initParamCount}, '${batch.sourceBaseId}')">
                    <i class="fa-solid fa-qrcode me-1"></i>生成人参溯源码
                </button>
            </td>
        `;
                tableBody.appendChild(row);
            });
        }

        // 生成溯源码
        function generateTraceCodes(batchNo, initParamCount, sourceBaseId) {
            if (!confirm(`确定要为批次 ${batchNo} 生成 ${initParamCount} 个溯源码吗？`)) {
                return;
            }

            // 显示加载中
            const button = event.target;
            const originalText = button.innerHTML;
            button.innerHTML = '<i class="fa-solid fa-spinner fa-spin me-1"></i>生成中...';
            button.disabled = true;

            // 发送AJAX请求
            fetch('${pageContext.request.contextPath}/production/generateTraceCodes', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    batchNo: batchNo,
                    initParamCount: initParamCount,
                    sourceBaseId: sourceBaseId
                })
            })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert(`成功生成 ${data.generatedCount} 个溯源码！`);
                        // 刷新表格数据
                        showSowHarvestModal();
                    } else {
                        alert('生成溯源码失败：' + data.message);
                        button.innerHTML = originalText;
                        button.disabled = false;
                    }
                })
                .catch(error => {
                    console.error('Error generating trace codes:', error);
                    alert('生成溯源码时发生错误');
                    button.innerHTML = originalText;
                    button.disabled = false;
                });
        }

        // 页面加载时绑定事件
        $(document).ready(function() {
            // 可以添加其他初始化代码
        });
    </script>
</body>
</html>
